package com.cmcc.speed.utils

import android.content.Context
import android.os.Environment
import android.util.Log
import android.webkit.WebView
import com.cmcc.speed.R
import okhttp3.*
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.jvm.internal.FunctionAdapter

object Speed {
    /**
    * 日志打印
    */
    fun log(vararg msg: Any?) {
        val nowTime = SimpleDateFormat("HH:mm:ss:SSS").format(System.currentTimeMillis())
        println("$nowTime [${Thread.currentThread().name}] ${msg.joinToString(" ")}")
    }

    /**
     * 下载
     */
    fun downloadFile(url: String, destFileDirName: String, progressBlock: ProgressBlock) {
        //下载状态  默认未开始
        var state: DownloadState = DownloadState.UnStart
        progressBlock(state)

        // TODO: 2021/12/27 file 创建与判断可以封装
        /**
         * file 创建判断  可以封装
         */
        val file = File(destFileDirName)
        val parentFile = file.parentFile
        if (!parentFile.exists()) {
            parentFile.mkdirs()
        }
        if (file.exists()) {
            //文件存在 不需要下载
            state = DownloadState.FileExistsNoDownload(file)
            progressBlock(state)
            return
        } else {
            file.createNewFile()
        }

        //下载
        val okHttpClient = OkHttpClient()
        val request = Request.Builder().url(url).build()
        okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                state = DownloadState.Failure(e)
                progressBlock(state)
            }

            override fun onResponse(call: Call, response: Response) {
                response.use { res ->
                    //完整长度
                    var totalLength = 0L
                    //写入字节
                    val bytes = ByteArray(2048)
                    val fileOutputStream = FileOutputStream(file)
                    res.body?.also { responseBody ->
                        totalLength = responseBody.contentLength()
                    }?.byteStream()?.let { inputStream ->
                        try {
                            var currentProgress = 0L
                            var len = 0
                            state = DownloadState.Progress(totalLength, currentProgress)
                            do {
                                if (len != 0) {
                                    currentProgress += len
                                    fileOutputStream.write(bytes)
                                }
                                //状态改变
                                (state as DownloadState.Progress).current = currentProgress
                                progressBlock(state)
                                len = inputStream.read(bytes, 0, bytes.size)
                            } while (len != -1)
                            //状态改变完成
                            state = DownloadState.Complete(file)
                            progressBlock(state)
                        } catch (e: Exception) {
                            state = DownloadState.Failure(e)
                            progressBlock(state)
                        } finally {
                            inputStream.close()
                            fileOutputStream.close()
                        }
                    }
                }
            }

        })

    }

}

/**
 * 下载状态机
 */
sealed class DownloadState {

    /**
     * 未开始
     */
    object UnStart : DownloadState()

    /**
     * 下载中
     */
    class Progress(var totalNum: Long, var current: Long) : DownloadState()

    /**
     * 下载完成
     */
    class Complete(val file: File?) : DownloadState()

    /**
     * 下载失败
     */
    class Failure(val e: Throwable?) : DownloadState()

    /**
     * 下载失败
     */
    class FileExistsNoDownload(val file: File?) : DownloadState()

}

/**
 * 进度通用回调  不使用flow封装的话 使用这个
 */
internal typealias ProgressBlock = (state: DownloadState) -> Unit